package com.example.orchid.paper.task;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.widget.Toast;

import java.io.FileNotFoundException;

import de.keyboardsurfer.android.widget.crouton.Crouton;
import de.keyboardsurfer.android.widget.crouton.Style;

/**
 * 将图片保存至系统图库Task
 * Created by Orchid on 2015-10-15.
 */
public class ImageToGalleryTask extends MyAsyncTask<String, Void, String> {
    private Activity mInstance;

    public ImageToGalleryTask(Activity instance) {
        mInstance = instance;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Toast.makeText(mInstance, "开始保存图片", Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        if (!TextUtils.isEmpty(s) && s.equals("success")) {
            Toast.makeText(mInstance, "图片已保存至相册", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(mInstance, "图片保存失败", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected String doInBackground(String... params) {
        if (params.length == 0) {
            return null;
        }

        boolean result = saveImage2Gallery(mInstance, params[0]);
        return result ? "success":"fail";
    }

    private boolean saveImage2Gallery(Context context, String imagePath) {
        boolean result = true;

        try {
            // 插入到系统图库
            MediaStore.Images.Media.insertImage(context.getContentResolver(), imagePath, "title", "desc..");
            // 通知图库更新
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + imagePath)));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            result = false;
        }

        return result;
    }
}
